class PublicController < ApplicationController

    def index
        return unless request.post?
        return if params[:link][:actual_url].empty?
        
        # if the record exists in database then get the shrinked url from the db
        @link = Link.find_by_actual_url(params[:link][:actual_url])
        
        # else create a new shrinked url and save in database
        unless @link
            @link = Link.create(params[:link])
            @link.shrinked_url = get_shrinked_url
            @link.save!
        end
        
        @link.shrinked_url = build_url(@link.shrinked_url)
        
    end
    
    def redirect
        link = Link.find_by_shrinked_url(params[:id])
        if link
            unless link.actual_url.include? 'http://'
                puts 'adding protocol'
                link.actual_url = "http://#{link.actual_url}" 
            end
            puts "Redirecting to #{link.actual_url}"
            redirect_to(link.actual_url)
        end
    end
  
    private
    def get_shrinked_url
        valid_chars = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9']
        code = ''
        (1..8).each do |i|
            char = valid_chars[rand(valid_chars.length)]
            code << char
        end
        code
    end
    
    def build_url(shrinked_id)
        @shrinked_url = "http://#{request.server_name}:#{request.server_port}/#{shrinked_id}"
    end
end
